/**
 * 
 */
package co.fitstart.api.handler.impl;


import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.demo2do.core.BusinessException;
import com.demo2do.core.utils.SignatureUtils;
import com.demo2do.core.utils.StringUtils;

import co.fitstart.api.handler.PaymentHandler;
import co.fitstart.entity.order.PaymentRequest;

/**
 * @author lute
 *
 */
@Component("checkoutHandler")
public class PaymentHandlerImpl implements PaymentHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(PaymentHandlerImpl.class);
    
    @Resource(name = "payment")
    private Properties properties;
    
    /**
     * 
     * @param paymentRequest
     * @return
     */
    private boolean checkSignature(PaymentRequest paymentRequest) {
        
        Map<String, String> params = paymentRequest.describe();
        
        String sortedQueryString = StringUtils.toSortedQueryString(params, "signature") + "&key=" + properties.getProperty("appsecret");
        logger.trace("CheckoutHandlerImpl#checkSignature() - Get sorted query string [{}].", sortedQueryString);
        
        String signature = SignatureUtils.makeMD5Signature(sortedQueryString).toUpperCase();
        logger.trace("CheckoutHandlerImpl#checkSignature() - Get new signature [{}], and the original signature is [{}].", signature, paymentRequest.getSignature());
        
        return org.apache.commons.lang3.StringUtils.equals(signature, paymentRequest.getSignature());
    }

    
    /*
     * (non-Javadoc)
     * @see co.fitstart.api.handler.PaymentCallbackHandler#check(co.fitstart.api.entity.PaymentRequest)
     */
    public void check(PaymentRequest paymentRequest) {
        
        // 1. Check all params
        if(!paymentRequest.isValid()) {
            throw new BusinessException("支付回调返回参数不完整");
        }
        
        // 2. check signature
        if(!this.checkSignature(paymentRequest)) {
            logger.error("#check() - Check oreder sync request signature fails...");
            throw new BusinessException("签名校验失败");
        }
    }


}
